<template>
  <div class="app-container">

    <el-button type="danger" size="mini" @click="onAdd()">添加</el-button>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row>
      <el-table-column align="center" label="序号" width="95" v-slot="scope">
          {{ scope.$index +1}}
      </el-table-column>
      <el-table-column prop="title" label="标题"/>
      <el-table-column label="图片"   align="center">
        <template slot-scope="scope">
          <img :src="scope.row.imageUrl" style="width: 150px" :alt="scope.row.title">
        </template>
      </el-table-column>
      <el-table-column prop="linkUrl" label="链接地址" align="center" v-slot="scope"/>
      <el-table-column class-name="status-col" label="排序"   align="center" v-slot="scope">
          <el-tag >{{ scope.row.sort }}</el-tag>
      </el-table-column>
      <el-table-column align="center"   label="添加时间" v-slot="scope">
          <i class="el-icon-time"/>
          <span>{{ scope.row.eduCreate+ ''}}</span>
      </el-table-column>
      <el-table-column align="center"  label="修改时间" v-slot="scope">
          <i class="el-icon-time"/>
          <span>{{ scope.row.eduModified+''}}</span>
      </el-table-column>
      <el-table-column align="center"  label="操作" v-slot="scope">
          <el-button type="primary" @click="handleClick(scope.row)" size="mini">修改</el-button>
          <el-button type="danger" @click="handleDelete(scope.row)" size="mini">删除</el-button>
      </el-table-column>

    </el-table>
    <div class="block">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page.sync="page.current"
        :page-size="page.size"
        layout="total, prev, pager, next"
        :total="page.total">
      </el-pagination>
    </div>

    <el-dialog
      title="添加轮播图"
      :visible.sync="dialogVisible"
      @close="handleClose"
      width="65%">

      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="标题" prop="title">
          <el-input v-model="ruleForm.title"></el-input>
        </el-form-item>
        <el-form-item label="上传图片" prop="file">
          <el-upload
            class="upload-demo"
            drag
            action="#"
            :show-file-list="false"
            :on-change="changeUpload"
            :auto-upload="false"
            >
            <i v-if="!imageUrl" class="el-icon-upload"></i>
            <img v-if="imageUrl"  :src="imageUrl" alt="" style="width: 100%;height: 100%;">


          </el-upload>
        </el-form-item>
        <el-form-item label="链接" prop="linkUrl">
          <el-input placeholder="请输入内容" v-model="ruleForm.linkUrl">
            <template slot="prepend">https://</template>
          </el-input>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input placeholder="值越小越靠前" type="number" min="1"  v-model="ruleForm.sort" ></el-input>
        </el-form-item>


        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>

  </div>
</template>

<script>


import {deleteById, getList, save} from '@/api/banner'

export default {

  data() {
    return {
      imageUrl:'',
      list: [],
      ruleForm: {
        id: '',
        title: '',
        imageUrl: '',
        linkUrl: '',
        sort: '',
        file: ''

      },
      rules: {
        title: [
          {required: true, message: '请输入标题', trigger: 'blur'},
        ],
        file: [
          {required: true, message: '请上传图片', trigger: 'blur'},
        ],
        sort: [
          {required: true, message: '排序必填', trigger: 'blur'},
          {pattern: /^[1-9]\d*$/, message: '必须是正整数', trigger: 'blur'},
        ],

      },
      listLoading: true,
      dialogVisible: false,
      page: {
        pages: '',
        current: 1,
        total: 0,
        size: 2
      },


    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    handleClose() {
      // 关闭弹出层时重置表单状态
      this.$refs.ruleForm.resetFields();

      //重置表单数据
      this.ruleForm={}
    },
    changeUpload(file){
      this.ruleForm.file=file.raw
      this.imageUrl = URL.createObjectURL(file.raw);
      this.$refs['ruleForm'].clearValidate(['file']); // 清除file字段的验证结果
      // 如果需要，可以移除或重置file字段的验证规则
      this.rules['file'] = null; // 移除规则
    },


    submitForm(formName) {


      this.$refs[formName].validate((valid) => {
        if (valid) {

          //用formdata的方式提交
          var formData = new FormData();
          var data = this.ruleForm;
          for(let key in data){
            formData.append(key,data[key])
          }
          save(formData).then( res =>{
            console.log(res);
            this.dialogVisible=false
            this.fetchData()
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    onAdd(){//添加

      this.imageUrl=""
      this.rules['file'] = [
        {required: true, message: '请上传图片', trigger: 'blur'},
      ];
      this.dialogVisible=true

    },
    handleClick(row) {//修改

      this.ruleForm.id=row.id
      this.ruleForm.title=row.title
      this.ruleForm.imageUrl=row.imageUrl
      this.ruleForm.sort=row.sort
      this.ruleForm.linkUrl=row.linkUrl
      this.imageUrl=row.imageUrl

      this.dialogVisible=true
      // 如果需要，可以移除或重置file字段的验证规则
      this.rules['file'] = null; // 移除规则
    },

    handleDelete(row){

      this.$confirm('此操作将删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        deleteById(row.id).then(response => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.fetchData()
        })


      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page.current=val
      this.getPage()

    },
    onSubmit() {
      console.log('submit!');
      this.getPage()

    },
    getPage(){
      getList(this.page.current,this.page.size).then(res => {
        this.list = res.data.records
        this.page = res.data
        this.listLoading = false
      })
    },
    fetchData() {
      this.listLoading = true
      this.getPage()
    }
  }
}

</script>

<style>
.banner-img {
  width: 100%;
  height: 178px;
  display: block;
}
</style>
